package com.xydtech.ecard.ecard.service.impl;

import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.utils.DateUtils;
import com.xydtech.ecard.config.mapper.EcardApiSysConfigMapper;
import com.xydtech.ecard.ecard.domain.*;
import com.xydtech.ecard.ecard.mapper.*;
import com.xydtech.ecard.ecard.service.IEcardApiMerchantVisitInfoService;
import com.xydtech.ecard.user.domain.EcardApiUserInfo;
import com.xydtech.ecard.user.mapper.EcardApiUserMapper;
import com.xydtech.system.domain.SysConfig;
import com.xydtech.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 电子名片商户拜访记录Service业务层处理
 *
 * @author xydtech
 * @date 2023-07-25
 */
@Slf4j
@Service
public class EcardApiMerchantVisitInfoServiceImpl implements IEcardApiMerchantVisitInfoService {
    @Autowired
    private EcardApiMerchantVisitInfoMapper ecardMerchantVisitInfoMapper;
    @Autowired
    private EcardApiMerchantTaskMapper ecardMerchantTaskMapper;

    @Autowired
    private EcardApiSysConfigMapper ecardApiSysConfigMapper;

    @Autowired
    private EcardApiMerchantInfoMapper ecardApiMerchantInfoMapper;

    @Autowired
    private EcardApiMerchantReservationTaskMapper ecardApiMerchantReservationTaskMapper;

    @Autowired
    private EcardApiEnterpriseInfoMapper ecardEnterpriseInfoMapper;

    @Autowired
    private EcardApiAgricultureInfoMapper ecardAgricultureInfoMapper;

    @Autowired
    private EcardApiPersonInfoMapper ecardPersonInfoMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private EcardApiUserMapper ecardApiUserMapper;

    /**
     * 查询个人/商户/企业/新型农业主体拜访记录
     *
     * @param id 电子名片商户拜访记录主键
     * @return 电子名片商户拜访记录
     */
    @Override
    public EcardApiMerchantVisitInfo selectEcardMerchantVisitInfoById(Long id) {
        return ecardMerchantVisitInfoMapper.selectEcardMerchantVisitInfoById(id);
    }

    /**
     * 查询电子名片个人/商户/企业/新型农业主体拜访记录列表
     *
     * @param ecardMerchantVisitInfo 电子名片商户拜访记录
     * @return 电子名片商户拜访记录
     */
    @Override
    public List<EcardApiMerchantVisitInfo> getMerchantVisitList(EcardApiMerchantVisitInfo ecardMerchantVisitInfo) {
        return ecardMerchantVisitInfoMapper.getMerchantVisitList(ecardMerchantVisitInfo);
    }

    /**
     * 新增电子名片个人/商户/企业/新型农业主体拜访记录
     *
     * @param ecardMerchantVisitInfo 电子名片商户拜访记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertEcardMerchantVisitInfo(EcardApiMerchantVisitInfo ecardMerchantVisitInfo) {
        try {
            int updateCount = ecardMerchantVisitInfoMapper.insertEcardMerchantVisitInfo(ecardMerchantVisitInfo);

            String merchantType = ecardMerchantVisitInfo.getMerchantType();//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            //判断是否存在代办任务
            List<EcardApiMerchantTask> apiMerchantTaskList = ecardMerchantTaskMapper.getMerchantTaskListById(ecardMerchantVisitInfo.getMerchantId(), merchantType);//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            if (apiMerchantTaskList.size() > 0) {
                for (int i = 0; i < apiMerchantTaskList.size(); i++) {
                    EcardApiMerchantTask apiMerchantTask = apiMerchantTaskList.get(i);
                    //存在就更新任务表数据
                    ecardMerchantTaskMapper.updateMerchantTaskSts(apiMerchantTask);
                }
            }
            //查询参数配置-拜访任务定时天数
            EcardApiUserInfo userInfo = ecardApiUserMapper.getUserInfo(String.valueOf(ecardMerchantVisitInfo.getCreatorId()));
            SysConfig config = new SysConfig();
            config.setConfigKey("ecard_merchant_task_days");
            //查询改为多法人，归属的县级法人机构
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            if (dept != null){
                config.setDeptId(dept.getDeptId());
            }
            SysConfig sysConfig = ecardApiSysConfigMapper.selectConfig(config);
            //判断下次回访日期是否小于拜访任务定时天数，小于则创建任务
            DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
            //开始日期
            String star = String.format("%tF", new Date());
            //结束时间
            String endDay = String.format("%tF", ecardMerchantVisitInfo.getReminderDate());
            int days = 0;
            try {
                days = DateUtils.differentDaysByMillisecond(dft.parse(star), dft.parse(endDay));
            } catch (ParseException e) {
                throw new RuntimeException();//抛出新的异常
            }
            if (days <= Integer.valueOf(sysConfig.getConfigValue())) {
                EcardApiMerchantTask merchantTask = new EcardApiMerchantTask();
                merchantTask.setMerchantId(ecardMerchantVisitInfo.getMerchantId());
                merchantTask.setCmRegistId(ecardMerchantVisitInfo.getCreatorId());
                merchantTask.setEndDate(ecardMerchantVisitInfo.getReminderDate());
                merchantTask.setMerchantType(merchantType);//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
                merchantTask.setTaskSts("0");
                ecardMerchantTaskMapper.insertEcardMerchantTask(merchantTask);
            }


            //修改商户办理成功的业务,添加到商户业务字段里面 1 代表营销成功
            if ("1".equals(ecardMerchantVisitInfo.getEcardSemResult()) && ecardMerchantVisitInfo.getNewBusiness() != null) {
                //商户类型：1-个人，2-商户，3-企业，4-新型农业主体加判断
                if ("1".equals(merchantType)) {//个人
                    EcardApiPersonInfo ecardApiPersonInfo = ecardPersonInfoMapper.selectEcardPersonInfoById(ecardMerchantVisitInfo.getMerchantId());
                    ecardApiPersonInfo.setPerBusinessLabel(ecardApiPersonInfo.getPerBusinessLabel() + "," + ecardMerchantVisitInfo.getNewBusiness());
                    ecardPersonInfoMapper.addPersonInfo(ecardApiPersonInfo);
                }
                if ("2".equals(merchantType)) {//商户
                    EcardApiMerchantInfo ecardApiMerchantInfo = ecardApiMerchantInfoMapper.selectEcardMerchantInfoById(ecardMerchantVisitInfo.getMerchantId());
                    ecardApiMerchantInfo.setBusinessLabel(ecardApiMerchantInfo.getBusinessLabel() + "," + ecardMerchantVisitInfo.getNewBusiness());
                    ecardApiMerchantInfoMapper.addMerchantInfo(ecardApiMerchantInfo);
                }
                if ("3".equals(merchantType)) {//企业
                    EcardApiEnterpriseInfo ecardApiEnterpriseInfo = ecardEnterpriseInfoMapper.selectEcardEnterpriseInfoById(ecardMerchantVisitInfo.getMerchantId());
                    ecardApiEnterpriseInfo.setEntBusinessLabel(ecardApiEnterpriseInfo.getEntBusinessLabel() + "," + ecardMerchantVisitInfo.getNewBusiness());
                    ecardEnterpriseInfoMapper.addEnterpriseInfo(ecardApiEnterpriseInfo);
                }
                if ("4".equals(merchantType)) {//新型农业主体
                    EcardApiAgricultureInfo ecardApiAgricultureInfo = ecardAgricultureInfoMapper.selectEcardAgricultureInfoById(ecardMerchantVisitInfo.getMerchantId());
                    ecardApiAgricultureInfo.setAgrBusinessLabel(ecardApiAgricultureInfo.getAgrBusinessLabel() + "," + ecardMerchantVisitInfo.getNewBusiness());
                    ecardAgricultureInfoMapper.addAgricultureInfo(ecardApiAgricultureInfo);
                }
            }
            //判断是否有预约业务任务
            if ("1".equals(ecardMerchantVisitInfo.getHasReservationBusi()) && ecardMerchantVisitInfo.getAppointmentDate() != null) {
                saveEcardMerchantReservationTask(ecardMerchantVisitInfo);
            }
            return updateCount;
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 判断预约时间是否小于配置的提前通知天数，若小于则生成该预约任务
     * @param ecardApiMerchantVisitInfo
     */
    private void saveEcardMerchantReservationTask(EcardApiMerchantVisitInfo ecardApiMerchantVisitInfo){
        //查询参数配置-预约任务定时天数
        EcardApiUserInfo userInfo = ecardApiUserMapper.getUserInfo(String.valueOf(ecardApiMerchantVisitInfo.getCreatorId()));
        SysConfig config = new SysConfig();
        config.setConfigKey("ecard_merchant_reservation_task_days");
        //查询改为多法人，归属的县级法人机构
        SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
        if (dept != null){
            config.setDeptId(dept.getDeptId());
        }
        SysConfig sysConfig = ecardApiSysConfigMapper.selectConfig(config);
        //判断下次回访日期是否小于拜访任务定时天数，小于则创建任务
        DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        //开始日期
        String star = String.format("%tF", new Date());
        //结束时间
        String endDay = String.format("%tF",  ecardApiMerchantVisitInfo.getAppointmentDate());
        int days = 0;
        try {
            days = DateUtils.differentDaysByMillisecond(dft.parse(star), dft.parse(endDay));
        } catch (ParseException e) {
            throw new RuntimeException();//抛出新的异常
        }
        if (days <= Integer.valueOf(sysConfig.getConfigValue())) {
            EcardApiMerchantReservationTask merchantReservationTask = new EcardApiMerchantReservationTask();
            merchantReservationTask.setMerchantId(ecardApiMerchantVisitInfo.getMerchantId());
            merchantReservationTask.setCmRegistId(ecardApiMerchantVisitInfo.getCreatorId());
            //预约业务类型
            merchantReservationTask.setReservationBusiType(ecardApiMerchantVisitInfo.getReservationBusiType());
            //预约日期
            merchantReservationTask.setAppointmentDate(ecardApiMerchantVisitInfo.getAppointmentDate());
            merchantReservationTask.setTaskSts("0");
            merchantReservationTask.setMerchantType(ecardApiMerchantVisitInfo.getMerchantType());//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            ecardApiMerchantReservationTaskMapper.insertEcardMerchantReservationTask(merchantReservationTask);
        }

    }

    /**
     * 定时任务-查询最近记录且回访日期为days天前的数据
     *
     * @author yjs
     * @date 2023/7/29 17:41
     */
    @Override
    public List<EcardApiMerchantVisitInfo> getMerchantLastVisitList(String days) {
        return ecardMerchantVisitInfoMapper.getMerchantLastVisitList(days);
    }

    @Override
    public List<EcardApiMerchantVisitInfo> getMerchantReservationList(String days) {
        return ecardMerchantVisitInfoMapper.getMerchantReservationList(days);
    }

    @Override
    public String getMerchantLastVisitTime(Long merchantId, String merchantType) {
        return ecardMerchantVisitInfoMapper.getMerchantLastVisitTime(merchantId, merchantType);
    }

    /**
     * 查询所有的拜访记录
     * @param ecardApiMerchantVisitInfo
     * @return
     */
    @Override
    public List<EcardApiMerchantVisitInfo> getAllVisitList(EcardApiMerchantVisitInfo ecardApiMerchantVisitInfo) {
        return ecardMerchantVisitInfoMapper.getAllVisitList(ecardApiMerchantVisitInfo);
    }

}
